package com.itheima.googleplay9.ui.fragment;

import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.itheima.googleplay9.R;
import com.itheima.googleplay9.adapter.CategoryAdapter;
import com.itheima.googleplay9.api.DataLoader;
import com.itheima.googleplay9.api.Url;
import com.itheima.googleplay9.bean.Category;
import com.itheima.googleplay9.bean.CategoryInfo;
import com.itheima.googleplay9.util.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lxj on 2016/5/23.
 */
public class CategoryFragment extends BaseFragment {
    //将title和CategoryInfo放入一个集合
    private ArrayList<Object> list = new ArrayList<>();
    private ListView listView;
    private CategoryAdapter categoryAdapter;
    @Override
    protected View getSuccessView() {
        listView = (ListView) View.inflate(getActivity(), R.layout.listview,null);

        //设置adapter
        categoryAdapter = new CategoryAdapter(list);
        listView.setAdapter(categoryAdapter);

        return listView;
    }

    @Override
    protected Object onLoad() {
        final ArrayList<Category> categories = (ArrayList<Category>) DataLoader.getInstance().loadListData(Url.Category,new TypeToken<List<Category>>(){}.getType());

        if(categories!=null){
            //将每个Category的title和CategoryInfo放入一个集合
            for (Category category : categories){
                //1.获取title，放入list集合
                list.add(category.getTitle());
                //2.将infos放入list中
                ArrayList<CategoryInfo> infos = category.getInfos();
                list.addAll(infos);
            }
            //最终组装好的数据如下：
            //title
            //CategoryInfo
            //CategoryInfo
            //CategoryInfo
            //title
            //CategoryInfo
            //CategoryInfo
            //CategoryInfo
            //CategoryInfo
            //CategoryInfo

            //更新UI
            Utils.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    categoryAdapter.notifyDataSetChanged();
                }
            });
        }
        return categories;

    }
}
